package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 查看购物车
     * @return
     */
    @Override
    public List<ShoppingCart> list() {
        ShoppingCart build = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> cartList = shoppingCartMapper.queryByParmas(build);
        return cartList;
    }

    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {
        Long userId = BaseContext.getCurrentId();
        ShoppingCart cart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,cart);
        cart.setUserId(userId);
        //1、根据前端传过来的参数进行查询
        List<ShoppingCart> cartList = shoppingCartMapper.queryByParmas(cart);
        //2、判断是否有结果集
        if (ObjectUtils.isNotEmpty(cartList)){
            //2.1如果有就在原有的数量上加一
            final ShoppingCart carts = cartList.get(0);
            carts.setNumber(carts.getNumber()+1);
            shoppingCartMapper.updateNumberById(carts);
        }else {
            //2.2如果没有就新增
            cart.setNumber(1);
            if (ObjectUtils.isNotEmpty(cart.getDishId())){
                final DishVO dishVO = dishMapper.queryById(cart.getDishId());
                cart.setName(dishVO.getName());
                cart.setImage(dishVO.getImage());
                cart.setAmount(dishVO.getPrice());
            }else if (ObjectUtils.isNotEmpty(cart.getSetmealId())){
                final SetmealVO setmealVO = setmealMapper.queryById(cart.getSetmealId());
                cart.setName(setmealVO.getName());
                cart.setImage(setmealVO.getImage());
                cart.setAmount(setmealVO.getPrice());
            }
            shoppingCartMapper.save(cart);
        }
    }

    /**
     * 清空购物车
     */
    @Override
    public void clean() {
        shoppingCartMapper.clean(BaseContext.getCurrentId());
    }
}
